package com.leo.netty.simple;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.CharsetUtil;

/**
 * @author du
 */
public class NettyClient {
    public static void main(String[] args) {

        // 客户端只需要一个事件循环组
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();

        try {
            // 客户端启动对象
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(eventLoopGroup)
                    .channel(NioSocketChannel.class) //设置客户端通道实现类(反射)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new ClientHandler());
                        }
                    });

            // 连接服务端, ChannelFuture涉及到Netty的异步线程模型, sync表示立马返回future对象
            ChannelFuture future = bootstrap.connect("127.0.0.1", 8888).sync();
            System.out.println("客户端已启动...");
            // 关闭通道事件监听
            future.channel().closeFuture().sync();

        } catch (Exception e) {

        } finally {
            eventLoopGroup.shutdownGracefully();
        }
    }

    private static class ClientHandler extends ChannelInboundHandlerAdapter {

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            //super.channelActive(ctx);
            ctx.writeAndFlush(Unpooled.copiedBuffer("hello, server.", CharsetUtil.UTF_8));
        }

        /**
         * 通道有读取事件时会触发
         * @param ctx ctx是一个上下文对象，包含了 pipeline/channel 对象的引用
         * @param msg 一般是ByteBuf对象
         */
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

            // 接收到的数据是一个ByteBuf对象, 需要强转
            ByteBuf buf = (ByteBuf) msg;
            System.out.println("服务器回复的消息是: " + buf.toString(CharsetUtil.UTF_8));
            System.out.println("服务器地址是: " + ctx.channel().remoteAddress());
        }
    }
}
